<?php
/**
 * @author       Sixe Team
 * @email        info@eee-eee.com
 * @url          http://www.eee-eee.com
 * @copyright    Copyright (C) 2010 - 2019 Sixe Information Technology Limited. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @date         2019/10/01 10:00
 */

defined('_JEXEC') or die;

use Joomla\Utilities\ArrayHelper;

/**
 * Content article class.
 *
 * @since  1.6.0
 */
class SixeWorkFlowControllerMessage extends JControllerForm
{
	public function CheckNew()
	{
		// Required objects
		$app=JFactory::getApplication();
		$user = JFactory::getUser();
		
			$db = JFactory::getDbo();
			$query = $db->getQuery(true)
			->select("a.id")
			->from('#__workflow_messages AS a ');
			$query->where('a.to_user='.(int)$user->id);
			$query->where('a.is_read=0');
			//$query->where('a.is_send=0');
			//echo $query;
			$db->setQuery($query);
			try
			{
				$results = $db->loadColumn();
			}
			catch (\RuntimeException $e)
			{
				echo $this->setError($e->getMessage());
			}
		

		if ($results)
		{
			// Output a JSON object
			$result=new stdclass;
			$result->count=count($results);
			$result->text='<span class="count">'.count($results).'</span><a href="'.JRoute::_('index.php?option=com_sixeworkflow&view=messages').'" class="link">'.JText::sprintf('COM_SIXEWORKFLOW_NEW_MESSAGE',count($results)).'</a>';
			echo json_encode($result);
		}
		else
		{
		$noresults=array();
		echo json_encode($noresults);
		}
		$app->close();
	}

	public function delete()
	{
		$return=false;
		$app=JFactory::getApplication();
		$id=$app->input->getInt('id',0);
		$user = JFactory::getUser();
		$db=JFactory::getDbo();
		$query=$db->getQuery(true);
		$query->select('to_user')
			->from('#__workflow_messages')
			->where('id='.$id);
		$db->setQuery($query);
		$user_id=$db->loadResult();
		if($user_id==$user->id)
		{
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_messages'))
				->where('id='.$id);
			$db->setQuery($query);
			$return=(boolean)$db->execute();
			if($return)
			{
				$this->setMessage(JText::_('COM_SIXEWORKFLOW_MESSAGES_DELETE_SUCCESS'), 'info');
			}
			else
			{
				$this->setMessage(JText::_('COM_SIXEWORKFLOW_MESSAGES_DELETE_ERROR'), 'error');
			}
		}
		else
		{
			$this->setMessage(JText::_('COM_SIXEWORKFLOW_MESSAGES_DELETE_USER_FALSE'), 'error');
		}




		$this->setRedirect(JRoute::_($this->getReturnPage(), false));


	}

	protected function getReturnPage()
	{
		$return = $this->input->get('return', null, 'base64');

		if (empty($return) || !JUri::isInternal(base64_decode($return)))
		{
			return JUri::root();
		}
		else
		{
			return base64_decode($return);
		}
	}

}
